mod config;
mod gpg;
mod http;
mod mirror;
mod storage;

use anyhow::Result;
use axum::Router;
use config::Config;
use std::sync::Arc;
use tokio::signal;

#[tokio::main]
async fn main() -> Result<()> {
    // 初始化彩色日志
    env_logger::builder()
        .format(|buf, record| {
            use colored::Colorize;
            use std::io::Write;
            
            let level = match record.level() {
                log::Level::Error => format!("[ERROR]").red().bold(),
                log::Level::Warn => format!("[WARN]").yellow().bold(),
                log::Level::Info => format!("[INFO]").blue().bold(),
                log::Level::Debug => format!("[DEBUG]").green().bold(),
                log::Level::Trace => format!("[TRACE]").cyan().bold(),
            };
            
            let timestamp = chrono::Local::now().format("%Y-%m-%d %H:%M:%S%.3f");
            writeln!(
                buf,
                "{} {} {}",
                timestamp.to_string().dimmed(),
                level,
                record.args()
            )
        })
        .init();
    
    log::info!("启动 Termux 镜像服务器");
    
    // 加载配置
    let config = Config::load_or_create("config.toml").await?;
    log::info!("配置加载成功");
    
    // 初始化存储
    let storage = storage::Storage::new(&config).await?;
    let storage = Arc::new(storage);
    
    // 检查 GPG 密钥
    gpg::check_gpg_keys(&config).await?;
    log::info!("GPG 密钥验证通过");
    
    // 启动镜像同步任务
    let mirror_config = config.clone();
    let mirror_storage = storage.clone();
    tokio::spawn(async move {
        mirror::run_mirror_task(mirror_config, mirror_storage).await;
    });
    
    // 创建 HTTP 服务
    let app = http::create_router(config.clone(), storage.clone());
    
    // 启动服务器
    let addr = format!("{}:{}", config.server.host, config.server.port)
        .parse()
        .expect("无效的服务器地址");
    
    log::info!("服务器监听地址: http://{}", addr);
    log::info!("镜像域名: {}", config.server.domain);
    log::info!("GPG 公钥地址: http://{}/gpg-key", config.server.domain);
    
    axum::Server::bind(&addr)
        .serve(app.into_make_service())
        .with_graceful_shutdown(shutdown_signal())
        .await?;
    
    Ok(())
}

async fn shutdown_signal() {
    let ctrl_c = async {
        signal::ctrl_c()
            .await
            .expect("无法安装 Ctrl+C 处理器");
    };
    
    #[cfg(unix)]
    let terminate = async {
        signal::unix::signal(signal::unix::SignalKind::terminate())
            .expect("无法安装信号处理器")
            .recv()
            .await;
    };
    
    #[cfg(not(unix))]
    let terminate = std::future::pending::<()>();
    
    tokio::select! {
        _ = ctrl_c => {},
        _ = terminate => {},
    }
    
    log::info!("优雅关闭服务器");
}